/**
 * Trix
 * <p/>
 * User: joakimd
 * Date: 2013-04-15
 * Time: 09:43
 */
package org.dru.masic.trix {
import flash.events.Event;
import flash.events.SampleDataEvent;
import flash.utils.ByteArray;

public class Trix {
    private var _sequencer:Sequencer;
    private var _empty: ByteArray;
    private var _buffer: ByteArray;
    private var _queue: Vector.<ByteArray>;
    private var _left:Vector.<Number>;
    private var _right:Vector.<Number>;
    private var _frame:int;

    public function Trix(sequencer:Sequencer) {
        _sequencer = sequencer;
        _empty = new ByteArray();
        for (var index: int = 0; index < 735 * 8; index++) {
            _empty.writeFloat(0.0);
            _empty.writeFloat(0.0);
        }
        _buffer = new ByteArray();
        _queue = new Vector.<ByteArray>();
        _left = new Vector.<Number>(735, true);
        _right = new Vector.<Number>(735, true);
        _frame = 0;
    }

    public function onEnterFrame(event: Event): void {
        _sequencer.work(_left, _right, 0, 735);
        for (var index: int = 0; index < 735; index++) {
            _buffer.writeFloat(_left[index]);
            _buffer.writeFloat(_right[index]);
        }
        _frame++;
        if (_frame == 8) {
            _frame = 0;
            _queue.push(_buffer);
            _buffer = new ByteArray();
        }

    }

    public function onSampleData(event: SampleDataEvent): void {
        if (_queue.length > 0) {
            play(_queue.splice(0, 1)[0], event.data);
        }
        else {
            play(_empty, event.data);
        }
    }

    private static function play(buffer: ByteArray, data: ByteArray): void {
        var length: int = buffer.position;
        buffer.position = 0;
        data.writeBytes(buffer, 0, length);
    }
}
}
